<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use think\facade\Log;
use think\model\concern\SoftDelete;

class BookInfo extends Common
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';

    protected $rule = [ 
        'book_price'   =>  'require|regex:/^[0-9]+(.[0-9]{1,2})?$/',
        'book_disc'   =>  'require|regex:/^[0-9]+(.[0-9]{1,2})?$/',
        'book_name'     => 'require',
        'book_author'   => 'require',
        'book_concern'  => 'require',
        'book_isbn'     => 'require',
        'book_edition'  => 'require',
        'book_date'     => 'require',
    ];
    protected $msg = [ 
        'book_price' => '请输入合法的单价',
        'book_disc' => '请输入正确的折扣信息',
        'book_name'     => '教材名称必填',
        'book_author'   => '主编必填',
        'book_concern'  => '出版社必填',
        'book_isbn'     => 'ISBN必填',
        'book_edition'  => '版次必填',
        'book_date'     => '出版年限必填',
    ];

    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'   => 'book_name',
                'desc' => '教材名称',
            ],
            [
                'id'   => 'book_price',
                'desc' => '教材单价',
            ],
            [
                'id'   => 'book_disc',
                'desc' => '折扣',
            ],
            [
                'id'   => 'book_author',
                'desc' => '主编',
            ],
            [
                'id'   => 'book_concern',
                'desc' => '出版社',
            ],
            [
                'id'   => 'book_isbn',
                'desc' => 'ISBN书号',
            ],
            [
                'id'   => 'book_edition',
                'desc' => '版次',
            ],
            [
                'id'   => 'book_date',
                'desc' => '出版年限',
            ],
            [
                'id'   => 'book_reward',
                'desc' => '获奖情况',
            ]
        ];
    }

    /**
     * 设置教材定价 csv header
     * @return array
     */
    public function csvPriceHeader()
    {
        return [
            [
                'id'   => 'book_isbn',
                'desc' => 'ISBN书号',
            ],
            [
                'id'   => 'book_price',
                'desc' => '教材单价',
            ]
        ];
    }
    
    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }


        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])
                    ->where($tableWhere['where'])
                    ->where($tableWhere['whereOr'])
                    ->order($tableWhere['order'])
                    ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    /**
     * 获取csv数据
     * @param $post
     * @return array
     */
    public function getExportData($post)
    {
        $result   = [
            'status' => false,
            'data'   => [],
            'msg'    => '无可导出用户'
        ]; 
 
        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])
                    ->where($tableWhere['where'])
                    ->where($tableWhere['whereOr'])
                    ->order($tableWhere['order'])
                    ->select();
                    
        if (count($list) > 0) {
            $result['status'] = true;
            $result['msg']    = '导出成功';
            $result['data']   = $list;
            return $result;
        } else {
            //失败，导出失败
            return $result;
        }
    }
    
    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        $whereOr = [];
        if(isset($post['book_name']) && $post['book_name'] != ""){
            $where[] = ['book_name', 'like', '%'.$post['book_name'].'%'];
        }

        if(isset($post['book_isbn']) && $post['book_isbn'] != ""){
            $where[] = ['book_isbn', 'eq', $post['book_isbn']];
        }

        if(isset($post['status']) && $post['status'] != ""){
            if($post['status'] == '0') {
                $whereOr = "isnull(book_price) is true or book_price = ''";
            } else if($post['status'] == '1') {
                $whereOr[] = ['book_price', 'egt','0'];
            } 
        }
 
        $result['where'] = $where;
        $result['whereOr'] = $whereOr;
        $result['field'] = "*";
        $result['order'] = ['utime desc'];
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        return $list;
    }

    public function getBookList()
    {
        return $this->field("id, concat(book_name, ' ', book_isbn) book_name")->select();
    }

    public function getBookNameList()
    { 
        $list = $this->field("book_name")->select();

        $isbnArray = $list->toArray();
        $isbnList = [];
        foreach ($isbnArray as $k => $v) {
            $isbnList[] = $v['book_name'];
        }
        return $isbnList;
    }

    public function getIsbnList()
    { 
        $list = $this->field("book_isbn")->select();

        $isbnArray = $list->toArray();
        $isbnList = [];
        foreach ($isbnArray as $k => $v) {
            $isbnList[] = $v['book_isbn'];
        }
        return $isbnList;
    }

    public function getBookInfoList()
    { 
        $list = $this->field("book_name, book_isbn")->select();

        $isbnArray = $list->toArray();
        $isbnList = [];
        foreach ($isbnArray as $k => $v) {
            $isbnList[$v['book_isbn'].'-'.$v['book_name']] = 1;
        }
        return $isbnList;
    }

    public function getBookPrice($id)
    {
        return $this->field("p.book_price")
            ->alias('b')
            ->join('book_price_import p', 'b.book_isbn = p.book_isbn')
            ->where(['b.id' => $id])->find()['book_price'];
    }

    public function addBookInfo($data)
    {
        $return = [
            'status' => false,
            'msg'    => '添加失败',
            'data'   => ''
        ];

        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $return['msg'] = $validate->getError();
            return $return;
        } 

        //判断ISBN号是否为13位有效数字
        if (!preg_match("/^\d{13}$/", $data['book_isbn'])) {
            $return['msg'] = 'ISBN书号必须为13位的纯数字，请规范填写！';
            return $return;
        }

        if($data['book_price'] <= 0) {
            $return['msg'] = '请输入合法的单价';
            return $return;
        }

        if($data['book_disc'] <= 0 || $data['book_disc'] > 1) {
            $return['msg'] = '请输入正确的折扣信息';
            return $return;
        }

        $newData['book_name'] = $data['book_name'];
        $newData['book_price'] = $data['book_price'];
        $newData['book_disc'] = $data['book_disc'];
        $newData['book_author'] = $data['book_author'];
        $newData['book_concern']   = $data['book_concern'];
        $newData['book_edition']   = $data['book_edition'];
        $newData['book_isbn']   = $data['book_isbn'];
        $newData['book_reward']   = $data['book_reward'];
        if($data['book_reward'] != '') {
            $newData['book_is_reward']   = 1; 
        } else {
            $newData['book_is_reward']   = 0; 
        }
        $newData['book_date']   = $data['book_date'];
        $this->save($newData);
        
        $return['status'] = true;
        $return['msg']    = '添加成功'; 

        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $return;
    }
    
    public function editBookInfo($data)
    {
        $return = [
            'status' => false,
            'msg'    => '保存失败',
            'data'   => ''
        ];

        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $return['msg'] = $validate->getError();
            return $return;
        } 

        //判断ISBN号是否为13位有效数字
        if (!preg_match("/^\d{13}$/", $data['book_isbn'])) {
            $return['msg'] = 'ISBN书号必须为13位的纯数字，请规范填写！';
            return $return;
        }

        if($data['book_price'] <= 0) {
            $return['msg'] = '请输入合法的单价';
            return $return;
        }

        if($data['book_disc'] <= 0 || $data['book_disc'] > 1) {
            $return['msg'] = '请输入正确的折扣信息';
            return $return;
        }

        $price = 0;
        $book_disc = 0;
        $book_info = $this->where(['id'=>$data['id']])->find();
        if($book_info) {
            $price = $book_info['book_price'];
            $book_disc = $book_info['book_disc'];
        }

        $newData['book_name'] = $data['book_name'];
        $newData['book_price'] = $data['book_price'];
        $newData['book_disc'] = $data['book_disc'];
        $newData['book_author'] = $data['book_author'];
        $newData['book_concern']   = $data['book_concern'];
        $newData['book_edition']   = $data['book_edition'];
        $newData['book_isbn']   = $data['book_isbn'];
        $newData['book_reward']   = $data['book_reward'];
        if($data['book_reward'] != '') {
            $newData['book_is_reward']   = 1; 
        } else {
            $newData['book_is_reward']   = 0; 
        }
        $newData['book_date']   = $data['book_date'];

        if (!$this->allowField(true)->save($newData,['id'=>$data['id']]))
        {
            $return['status'] = false;
            $return['msg']    = '保存失败'; 
        } else {
            if($price != $newData['book_price']){
                // 更新所有涉及到的价格信息
                $model = new Common();
                $model->query("call BookPriceChange('".$data['id']."');");
            }
            if($book_disc != $newData['book_disc']){
                // 更新所有涉及到的折扣信息
                $model = new Common();
                $model->query("call BookDiscChange('".$data['id']."');");
            }

            $return['status'] = true;
            $return['msg']    = '保存成功'; 
        }

        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $return;
    }
}